using System.Drawing;
using System.Windows.Forms;
using Core;
using SdlDotNet.Graphics;

namespace SpaceEdit
{
    public partial class EditorControl : UserControl
    {
        public event OnSelectHandler OnSelect;

        private Surface RenderingSurface;
        private GameObject selectedObject;
        private Game game;

        public GameObject SelectedObject
        {
            get { return selectedObject; }
            set
            {
                selectedObject = value;
            }
        }

        public EditorControl()
        {
            InitializeComponent();
            
            RenderingSurface = new Surface(Width, Height, 24);
        }

        public Game Game
        {
            get { return game; }
            set { game = value; }
        }

        public void Render()
        {
            RenderingSurface.Fill(Color.Black);
            foreach (GameObject obj in Game.Objects)
            {
                RenderingSurface.Blit(obj.Render(), new Point(obj.Position.X, obj.Position.Y));
            }

            DisplaySurface.Blit(RenderingSurface);
        }

        private void DisplaySurface_MouseClick(object sender, MouseEventArgs e)
        {
            Point position = new Point(e.X - Top, e.Y - Left);
            foreach(GameObject obj in Game.Objects)
            {
                if (obj.Hit(position))
                {
                    SelectedObject = obj;
                    OnSelect(this, new OnSelectHandlerArgs(obj));
                }

                return;
            }

            SelectedObject = null;
        }
    }

    public delegate void OnSelectHandler(object sender, OnSelectHandlerArgs args);

    public class OnSelectHandlerArgs
    {
        private GameObject selectedObject;
        public GameObject SelectedObject
        {
            get { return selectedObject; }
        }

        public OnSelectHandlerArgs() {}
        public OnSelectHandlerArgs(GameObject obj) : this()
        {
            selectedObject = obj;
        }
    }
}
